﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 杂项_出库明签收明细回写
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMSAddShipInfoAndReceiptController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_wms_zh;
        public readonly string con_wms_qh;
        public readonly string con_wms_sc;
        public readonly string con_erp;
        public readonly string con_wms_gd;
        public readonly string con_wms_gz;
        public readonly string con_wms_fl;


        public TMSAddShipInfoAndReceiptController(ILogger<TMSAddShipInfoAndReceiptController> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_wms_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_wms_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_wms_sc = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_erp = _configuration.GetConnectionString("ERP_DbConnection");
            con_wms_gd = _configuration.GetConnectionString("WMSDbConnection_GD");
            con_wms_gz = _configuration.GetConnectionString("WMSDbConnection_GZ");
            con_wms_fl = _configuration.GetConnectionString("FL_DbConnection");
            _logger = loggerFactory.CreateLogger<TMSAddShipInfoAndReceiptController>();
        }

        /// <summary>
        /// 杂项_出库明签收明细回写
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddShipInfoAndReceipt([FromBody] TMSAddShipInfoAndReceiptRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            TMtoWMSAddCarInfoResponseDto re = new TMtoWMSAddCarInfoResponseDto();
            string waybill_no = strparm.waybill_no;
            try
            {
                if (waybill_no == "")
                {
                    strMsg = "waybill_no must be not null";
                }               

                if (strMsg == "")
                {
                    dic = new Dictionary<string, string>(); //查询公用dic
                    dic.Add("waybill_no", waybill_no);//查询对应物流计划
                    DataTable tms_wj = MethodHelp.GetTableInfo("TMS0127", dic, con);//获取物流发运单明细，外键ID信息
                    if (tms_wj.Rows.Count>0)
                    {
                        dic = new Dictionary<string, string>();
                        dic.Add("waybill_no", waybill_no);
                        string strsql1 = MethodHelp.GetTranSQL("TMS0078", dic, con);
                        if (strsql1 != "")
                        {
                            strSqlList.Add(strsql1.ToString());
                        }
                        else
                        {
                            strMsg = "Parameter conversion failed";
                        }

                        if (strMsg=="")
                        {
                            dic = new Dictionary<string, string>();
                            dic.Add("waybill_no", waybill_no);
                            DataTable dt_rp = MethodHelp.GetTableInfo("TMS0093", dic, con);
                            if (dt_rp.Rows.Count <= 0)
                            {
                                //签收明细插入
                                foreach (DataRow row in tms_wj.Rows)
                                {
                                    dic = new Dictionary<string, string>();
                                    //基础ID信息
                                    dic.Add("tab_doc_id", row["tab_doc_id"].ToString());
                                    dic.Add("status", row["status"].ToString());
                                    dic.Add("tenant_id", row["tenant_id"].ToString());
                                    dic.Add("form_id", row["form_id"].ToString());
                                    dic.Add("process_id", row["process_id"].ToString());
                                    dic.Add("owner", row["owner"].ToString());
                                    //业务数据
                                    dic.Add("waybill_no", row["waybill_no"].ToString());
                                    dic.Add("customer_name", row["customer_name"].ToString());
                                    dic.Add("delivery_address", row["delivery_address"].ToString());
                                    dic.Add("receipt_no", row["receipt_no"].ToString());
                                    dic.Add("qty", row["qty"].ToString());
                                    string strSQL = MethodHelp.GetTranSQL("TMS0076", dic, con);
                                    if (strSQL != "")
                                    {
                                        strSqlList.Add(strSQL.ToString());
                                    }
                                    else
                                    {
                                        strMsg = "Parameter conversion failed";
                                    }                                  
                                }
                            }

                            if (strMsg == "")
                            {
                                foreach (DataRow row2 in tms_wj.Rows)
                                {
                                    dic = new Dictionary<string, string>();
                                    //基础ID信息
                                    dic.Add("tab_doc_id", tms_wj.Rows[0]["tab_doc_id"].ToString());
                                    dic.Add("status", tms_wj.Rows[0]["status"].ToString());
                                    dic.Add("tenant_id", tms_wj.Rows[0]["tenant_id"].ToString());
                                    dic.Add("form_id", tms_wj.Rows[0]["form_id"].ToString());
                                    dic.Add("process_id", tms_wj.Rows[0]["process_id"].ToString());
                                    dic.Add("owner", tms_wj.Rows[0]["owner"].ToString());
                                    //业务数据
                                    dic.Add("waybill_no", waybill_no);
                                    dic.Add("plan_no", row2["plan_no"].ToString());
                                    dic.Add("customer_code", row2["customer_code"].ToString());
                                    dic.Add("customer_name", row2["customer_name"].ToString());
                                    dic.Add("saleorder_no", "");
                                    dic.Add("saleorderline_no", "");
                                    dic.Add("material_code", row2["material_code"].ToString());
                                    dic.Add("material_name", row2["material_name"].ToString());
                                    dic.Add("qty", row2["qty"].ToString());
                                    dic.Add("delivery_no", row2["receipt_no"].ToString());
                                    dic.Add("saleorderline_id", "");
                                    dic.Add("end_custom", row2["customer_name"].ToString());
                                    dic.Add("end_saleorderno", "");
                                    dic.Add("end_saleorderlineno", "");
                                    dic.Add("delivery_address", row2["delivery_address"].ToString());
                                    //string strSQL = MethodHelp.GetTranSQL("TMS0075", dic, con);
                                    string strSQL2 = MethodHelp.GetTranSQL("TMS0096", dic, con);
                                    if (strSQL2 != "")
                                    {
                                        strSqlList.Add(strSQL2.ToString());
                                    }
                                    else
                                    {
                                        strMsg = "Parameter conversion failed";
                                    }
                                }
                               
                            }
                        }

                        if (strSqlList.Count > 1)
                        {
                            bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                            if (A)
                            {

                            }
                            else
                            {
                                strMsg = "Database update failed";
                            }
                        }
                        else
                        {
                            strMsg = "No insertion data present";
                        }
                    }
                    else
                    {
                        strMsg = "运单号=<" + waybill_no + "> 获取订单明细失败，请确认后再试!";
                    }                                                               
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
